#!/usr/bin/env bash

#
# install docker cli binary
#

################################################################################

DOCKER_VERSION=${1:-20.10.1}
DOCKER_BUILDX_VERSION=0.5.1
################################################################################

set -ex

__test(){
  docker --version
  docker buildx
}

_sudo(){
  command -v sudo > /dev/null && echo "sudo" || true
}

command -v curl || $(_sudo) apt install curl tar

command -v docker && DOCKER_CURRENT_VERSION=$( docker --version | cut -d ' ' -f 3 ) \
                  && test "${DOCKER_CURRENT_VERSION}" = "$DOCKER_VERSION," && __test && exit 0;

cd /tmp

download_docker(){
  curl -SL https://mirrors.ustc.edu.cn/docker-ce/linux/static/test/x86_64/docker-${DOCKER_VERSION}.tgz | tar -zxvf -
}

if [ -d docker ];then
  DOCKER_CURRENT_VERSION=$( docker/docker --version | cut -d ' ' -f 3 )

  if [ $DOCKER_VERSION, != $DOCKER_CURRENT_VERSION ];then
    download_docker
  fi

else
  download_docker
fi

$(_sudo) cp docker/docker /usr/local/bin/docker

# 命令行补全

if ! [ -d /etc/bash_completion.d ];then $(_sudo) mkdir -p /etc/bash_completion.d; fi

if ! [ -f /etc/bash_completion.d/docker ];then

$(_sudo) curl -L https://raw.githubusercontent.com/docker/docker-ce/master/components/cli/contrib/completion/bash/docker -o /etc/bash_completion.d/docker

fi

# verify

mkdir -p ~/.docker/cli-plugins

test -f ~/.docker/cli-plugins/docker-buildx || curl -fSsL https://github.com/docker/buildx/releases/download/v${DOCKER_BUILDX_VERSION}/buildx-v${DOCKER_BUILDX_VERSION}.linux-amd64 -o ~/.docker/cli-plugins/docker-buildx

chmod +x ~/.docker/cli-plugins/docker-buildx

__test
